package com.situ.allaia.controller;

import com.github.pagehelper.util.StringUtil;
import com.situ.allaia.common.Global;
import com.situ.allaia.interceptor.LoginInterceptor;
import com.situ.allaia.model.CartItem;
import com.situ.allaia.model.User;
import com.situ.allaia.service.CartService;
import com.situ.allaia.service.UserService;

import com.wf.captcha.*;
import com.wf.captcha.base.Captcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/login")
    public String login(HttpSession session, Map<String, Object> map) {
        String error = (String) session.getAttribute("error");
        if (StringUtils.hasText(error)){
            map.put("error",error);
            session.removeAttribute("error");
        }
        return "login";
    }

    @PostMapping(value = "/login")
    public String login(User user, String captcha,HttpServletRequest req) {
        //todo:校验
        HttpSession session = req.getSession();
        if (!StringUtils.hasText(user.getUsername())){
            session.setAttribute("error","用户名不可为空");
            return "redirect:" + req.getContextPath() + "/user/login";
        }
        if (!StringUtils.hasText(user.getPassword())){
            session.setAttribute("error","密码不可为空");
            return "redirect:" + req.getContextPath() + "/user/login";
        }
        String correct = (String) session.getAttribute("captcha");
        if (!StringUtils.hasText(captcha)){
            session.setAttribute("error","验证码不能为空");
            return "redirect:" + req.getContextPath() + "/user/login";
        }
        if (!correct.equals(captcha)){
            session.setAttribute("error","验证码不正确");
            return "redirect:" + req.getContextPath() + "/user/login";
        }
        User dbUser = userService.findByUsername(user.getUsername());
        if (dbUser == null){
            session.setAttribute("error","用户不存在");
            return "redirect:" + req.getContextPath() + "/user/login";
        }else{
            String encript = user.getPassword() +"{" + user.getUsername() + "}";
            encript = DigestUtils.md5DigestAsHex(encript.getBytes(StandardCharsets.UTF_8));
            if (!dbUser.getPassword().equals(encript)){
                session.setAttribute("error","密码不正确");
                return "redirect:" + req.getContextPath() + "/user/login";
            }
        }
        session.setAttribute(LoginInterceptor.CURRENT_LOGIN_USER_KEY,dbUser);
        String redirectUrl = (String)session.getAttribute("redirectUrl");
        session.removeAttribute("redirectUrl");
        if (redirectUrl!=null&&redirectUrl!=""){
            return "redirect:" + req.getContextPath() + redirectUrl;
        }else {
            return "redirect:" + req.getContextPath() + "/";
        }
    }

    @GetMapping("/captcha")
    private void captcha(HttpServletRequest req, HttpServletResponse resp) throws IOException, FontFormatException {
        resp.setContentType("image/gif");
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0L);
        HttpSession session = req.getSession();
        SpecCaptcha captcha = new SpecCaptcha(130,50,4);
        captcha.setFont(Captcha.FONT_3);
        captcha.setFont(new Font("苹方-简", Font.PLAIN, 30));
        session.setAttribute("captcha",captcha.text().toLowerCase());
        captcha.out(resp.getOutputStream());

////        // 三个参数分别为宽、高、位数
//        ChineseGifCaptcha chineseGifCaptchaAbstract = new ChineseGifCaptcha(130,28,4);
//        chineseGifCaptchaAbstract.setFont(new Font("楷体", Font.PLAIN, 20));
//        // 获取验证码
//        session.setAttribute("captcha",chineseGifCaptchaAbstract.text().toLowerCase());
//        // 输出图片流
//        chineseGifCaptchaAbstract.out(resp.getOutputStream());
    }
    @GetMapping("/logout")
    public String logout(HttpSession session,HttpServletRequest req){
        session.removeAttribute(LoginInterceptor.CURRENT_LOGIN_USER_KEY);
        return "redirect:" + req.getContextPath() +"/";
    }
    @GetMapping("/register")
    public String register(HttpSession session, Map<String, Object> map) {
        String error = (String) session.getAttribute("error");
        if (StringUtils.hasText(error)){
            map.put("error",error);
            session.removeAttribute("error");
        }
        return "register";
    }
    @PatchMapping(value = "/edit",produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String,Object> edit(User user,HttpServletRequest req){
        HttpSession session = req.getSession();
        User oldUser = Global.findUser(session);
        if (!StringUtils.hasText(user.getUsername())){
            return Map.of("success",false,"error","用户名不能为空");
        }
        if (!StringUtils.hasText(user.getPassword())){
            return Map.of("success",false,"error","原密码不能为空");
        }
        String encrypt = user.getPassword() + "{" + user.getUsername()+"}";
        encrypt = DigestUtils.md5DigestAsHex(encrypt.getBytes(StandardCharsets.UTF_8));
        if (!oldUser.getPassword().equals(encrypt)){
            return Map.of("success",false,"error","原密码错误");
        }
        //todo:电话格式检验
        String newPassword = req.getParameter("newPassword");
        if (!StringUtils.hasText(newPassword)){
            return Map.of("success",false,"error","新密码不能为空");
        }
        //todo:新密码校验
        user.setId(oldUser.getId());
        user.setPassword(newPassword);
        user.setSex(oldUser.getSex());
        user.setIsVip(oldUser.getIsVip());
        user.setIsLock(oldUser.getIsLock());
        user.setDescription(oldUser.getDescription());
        boolean success = userService.update(user);
        return Map.of("success",success);
    }
}
